package edu.uclm.esi.tysweb.ajedrez.persistencia;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import edu.uclm.esi.tysweb.ajedrez.dominio.Tablero;
import edu.uclm.esi.tysweb.ajedrez.dominio.Jugador;;

public class DAOTablero {
	
	public static void registrar(int idTablero,int idB,int idN,String contenido) throws SQLException {
		Connection bd=Broker.get().getDBPrivilegiada();
		try {
			String sql="Insert into tablero (id, idJugadorBlancas, idJugadorNegras, contenido, idJugadorGanador) values (?, ?, ?, ?, ?)"; //Cambiar procedure
			PreparedStatement cs=bd.prepareStatement(sql);
			cs.setInt(1, idTablero);
			cs.setInt(2, idB);
			cs.setInt(3, idN);
			cs.setString(4, contenido);
			cs.setString(5, null);
			cs.executeUpdate();

		}
		catch (SQLException e) {
			throw e;
		}
		finally {
			bd.close();
		}
	}
	
	public static void saveMove(int idTablero,String mov) throws SQLException {
		Connection bd=Broker.get().getDBPrivilegiada();
		try {
			String sql="Insert into movimiento (idTablero, contenido) values (?, ?)"; //Cambiar procedure
			PreparedStatement cs=bd.prepareStatement(sql);
			cs.setInt(1, idTablero);
			cs.setString(2, mov);
			cs.executeUpdate();

		}
		catch (SQLException e) {
			throw e;
		}
		finally {
			bd.close();
		}
	}
	

	public static Connection identificar(String email, String pwd) throws SQLException {
		return Broker.get().getDB(email, pwd);
	}


	public static int lastId() throws SQLException {
		Connection bd=Broker.get().getDBPrivilegiada();
		int idSend=0;
		try {
			String sql="Select id from tablero order by id desc limit 1"; //Cambiar procedure
			PreparedStatement cs=bd.prepareStatement(sql);
			ResultSet r=cs.executeQuery();
			if (r.first()){
				idSend=r.getInt(1);
			}
		}
		catch (SQLException e) {
			throw e;
		}
		finally {
			bd.close();
		}
		return idSend;
	}
	
	
	public static void update(int idTablero,String contenido,int ganador) throws SQLException {
		Connection bd=Broker.get().getDBPrivilegiada();
		try{	
			String sql="Update tablero set contenido=?,idJugadorGanador=? where id=?"; //Cambiar select para tablero
			PreparedStatement ps=bd.prepareStatement(sql);
			ps.setString(1, contenido);
			if(ganador!=0)
				ps.setInt(2, ganador);
			else
				ps.setString(2,null);
			ps.setInt(3, idTablero);
			ps.executeUpdate();
		}
		catch (SQLException e) {
			throw e;
		}
		finally {
			bd.close();
		}
	}
}
